package com.konsung.ksdc.manager.appmain;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.SaleServiceNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.OnItemMultiClickListener;
import com.konsung.ksdc.common.widget.OnMultiClickListener;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.saleservice.AddProblemActivity;
import com.konsung.ksdc.manager.saleservice.ProblemListAdapter;
import com.konsung.ksdc.manager.saleservice.SaleServiceDetailActivity;

import java.util.List;

import butterknife.Bind;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.util.PtrLocalDisplay;
import okhttp3.Call;

/**
 * 售后服务主界面
 * Created by andy on 2017/4/13.
 */

public class SaleServiceFragment extends BaseFragment {
    public static final String SALE_SERVICE_NETBEAN = "sale_detail_reply";
    public static final String SALE_SERVICE_DATE = "sale_detail_date";
    public static final String SALE_SERVICE_ID = "sale_service_id";
    @Bind(R.id.lv_problem_message_list)
    ListView lvProblemMessageList;
    @Bind(R.id.ll_empty)
    LinearLayout llEmpty;
    @Bind(R.id.iv_abnormal)
    ImageView ivOpinion;
    @Bind(R.id.tv_abnormal_type)
    TextView tvOpinion;
    @Bind(R.id.tv_abnormal_text)
    TextView tvDeclare;
    @Bind(R.id.btn_go)
    Button btnFlush;
    @Bind(R.id.tab_tv_title)
    public TextView mTvTitle;
    @Bind(R.id.iv_add_new)
    protected ImageView ivAddNew;
    @Bind(R.id.rl_back)
    protected RelativeLayout mIvBack;
    @Bind(R.id.ptr_resflsh)
    protected PtrFrameLayout ptrFrameLayout;
    private static final int MSG_HAS_MACHINE = 1;
    private static final int MSG_MACHINE_NULL = 2;
    private static final int MSG_SALE_RECORDS = 3;
    private static final int MSG_SALE_RECORD_NULL = 4;
    private static final int MSG_NETWORK_FAIL = 5; // 网路断开显示UI
    private static final int MSG_SERVER_LOST = 6; // 服务器访问失败
    private List<SaleServiceNetBean> saleServiceNetBeanList;
    private boolean isRefsh; //是否下拉刷新
    private ProblemListAdapter problemListAdapter; //适配器
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_HAS_MACHINE:
                    ivAddNew.setVisibility(View.VISIBLE);
                    Intent intent = new Intent(getActivity(),
                            AddProblemActivity.class);
                    getActivity().startActivity(intent);
                    break;
                case MSG_MACHINE_NULL:
                    ivAddNew.setVisibility(View.VISIBLE);
                    ToastUtils.toastContent(getActivity(), getActivity().getString(R.string
                            .tip_machine_null));

                    break;
                case MSG_SALE_RECORDS:
                    ivAddNew.setVisibility(View.VISIBLE);
                    llEmpty.setVisibility(View.GONE);
                    lvProblemMessageList.setVisibility(View.VISIBLE);
                    if (isRefsh) {
                        //刷新
                        isRefsh = false;
                        problemListAdapter.refreshData(saleServiceNetBeanList);
                    } else {
                        //重新设置界面
                        problemListAdapter.setData(saleServiceNetBeanList);
                        lvProblemMessageList.setAdapter(problemListAdapter);
                    }
                    break;
                case MSG_SALE_RECORD_NULL:
                    // 暂无售后记录
                    ivAddNew.setVisibility(View.VISIBLE);
                    llEmpty.setVisibility(View.VISIBLE);
                    lvProblemMessageList.setVisibility(View.GONE);
                    ivOpinion.setImageResource(R.drawable.no_opinion);
                    tvOpinion.setText(R.string.after_no_record);
                    tvDeclare.setVisibility(View.INVISIBLE);
                    btnFlush.setVisibility(View.INVISIBLE);

                    break;
                case MSG_NETWORK_FAIL:
                    ivAddNew.setVisibility(View.VISIBLE);
                    llEmpty.setVisibility(View.VISIBLE);
                    tvDeclare.setVisibility(View.VISIBLE);
                    btnFlush.setVisibility(View.VISIBLE);
                    lvProblemMessageList.setVisibility(View.GONE);
                    ivOpinion.setImageResource(R.drawable.after_no_wifi);
                    tvOpinion.setText(R.string.wifi_not_well);
                    tvDeclare.setText(R.string.check_your_network);
                    btnFlush.setText(R.string.refresh);
                    break;
                case MSG_SERVER_LOST:
                    //进度条消失
                    ToastUtils.toastContent(MyApplication.getContext(), MyApplication
                            .getContext().getString(R.string.chat_unconnect));
                    ivAddNew.setVisibility(View.VISIBLE);
                    llEmpty.setVisibility(View.VISIBLE);
                    tvDeclare.setVisibility(View.VISIBLE);
                    btnFlush.setVisibility(View.VISIBLE);
                    lvProblemMessageList.setVisibility(View.GONE);
                    ivOpinion.setImageResource(R.drawable.after_server_fail);
                    tvOpinion.setText(R.string.get_data_fail);
                    tvDeclare.setVisibility(View.INVISIBLE);
                    btnFlush.setText(R.string.reload);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        problemListAdapter = new ProblemListAdapter();
    }

    /**
     * 加载数据
     */
    protected void initData() {
        mTvTitle.setText(R.string.title_activity_aftersell);
        // 网络断开
        if (!RequestUtils.checkNetwork(getActivity())) {
            // 显示网络断开的图片
            handler.sendEmptyMessage(MSG_NETWORK_FAIL);
            return;
        }
        // 加载数据
        RequestUtils.findSaleServiceByEmpId(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        handler.sendEmptyMessage(MSG_SERVER_LOST);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            saleServiceNetBeanList = responseBean.getList(new
                                    TypeToken<List<SaleServiceNetBean>>() {
                                    }.getType());
                            if (saleServiceNetBeanList.size() > 0) {
                                handler.sendEmptyMessage(MSG_SALE_RECORDS);
                            } else {
                                handler.sendEmptyMessage(MSG_SALE_RECORD_NULL);
                            }
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void initEvent() {
        mIvBack.setVisibility(View.GONE);
        // 重新加载数据
        if (btnFlush != null) {
            btnFlush.setVisibility(View.VISIBLE);
            btnFlush.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (RequestUtils.isNetworkConnected(getActivity())) {
                        // 重新加载
                        initData();
                    } else {
                        ToastUtils.toastContent(getActivity(),
                                getActivity().getString(R.string.tip_check_net));
                    }
                }
            });
        }

        if (ivAddNew != null) {
            ivAddNew.setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View v) {
                    Intent intent = new Intent(getActivity(),
                            AddProblemActivity.class);
                    startActivity(intent);
                }
            });
        }

        lvProblemMessageList.setOnItemClickListener(new OnItemMultiClickListener() {
            @Override
            public void onItemMultiClick(AdapterView<?> parent, View view, int position, long id) {
                // 点击单个条目,进入详情页面
                String serviceId = saleServiceNetBeanList.get(position).getId();
                // 用户反馈日期
                String date = saleServiceNetBeanList.get(position).getCreateDate().split("&")[0];
                Intent intent = new Intent(getActivity(), SaleServiceDetailActivity.class);
                intent.putExtra(SALE_SERVICE_ID, serviceId);
                // 将日期传过去
                intent.putExtra(SALE_SERVICE_DATE, date);
                getActivity().startActivity(intent);
            }
        });
        //刷新控件事件
        initPtr();
    }

    /**
     * 刷新数据
     */
    private void initPtr() {
        /**
         * 经典 风格的头部实现
         */
        final PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(getActivity());
        header.setPadding(0, PtrLocalDisplay.dp2px(15), 0, 0);
        header.setBackgroundResource(R.color.refresh_bg);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(new PtrHandler() {

            //需要加载数据时触发
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptrFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefsh = true;
                        //刷新数据
                        refreshData();
                    }
                }, 1800);
            }

            /**
             * 检查是否可以执行下来刷新，比如列表为空或者列表第一项在最上面时。
             */
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
    }

    /**
     * 重新刷新数据
     */
    private void refreshData() {
        // 网络断开
        if (!RequestUtils.checkNetwork(getActivity())) {
            isRefsh = false;
            //刷新停止
            ptrFrameLayout.refreshComplete();
            // 显示网络断开的图片
            handler.sendEmptyMessage(MSG_NETWORK_FAIL);
            return;
        }
        // 加载数据
        RequestUtils.findSaleServiceByEmpId(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        isRefsh = false;
                        ptrFrameLayout.refreshComplete();
                        handler.sendEmptyMessage(MSG_SERVER_LOST);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        //刷新停止
                        ptrFrameLayout.refreshComplete();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            saleServiceNetBeanList = responseBean.getList(new
                                    TypeToken<List<SaleServiceNetBean>>() {
                                    }.getType());
                            if (saleServiceNetBeanList.size() > 0) {
                                handler.sendEmptyMessage(MSG_SALE_RECORDS);
                            } else {
                                handler.sendEmptyMessage(MSG_SALE_RECORD_NULL);
                            }
                        }
                    }
                });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_aftersell;
    }
}
